package com.lyons.easyweb.modular.fileInfo;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyons.easyweb.core.util.LayuiPageInfo;
import com.lyons.easyweb.modular.fileInfo.pojo.FileInfo;
import com.lyons.easyweb.modular.fileInfo.service.FileInfoService;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;

/**
 * <p>
 * 文件信息表 前端控制器
 * </p>
 *
 * @author Lyons
 * @since 2021-07-01
 */
@RestController
@RequestMapping("/sys/file")
public class FileInfoController {

	@Autowired
	private FileInfoService fileInfoService;

	@RequestMapping("/upload")
	public LayuiPageInfo upload(MultipartFile file) throws IllegalStateException, IOException {

		String path = fileInfoService.upload(file);

		return LayuiPageInfo.ok("文件上传成功 !", path);
	}

	@RequestMapping("/download")
	public void download(String id, HttpServletRequest request, HttpServletResponse response) throws Exception {

		FileInfo fileInfo = fileInfoService.getById(id);
		
		request.setCharacterEncoding("utf-8");
		// 从请求中获取文件名
		String fileName = fileInfo.getFileOriginName();

		// 文件存储路径
		String path = fileInfo.getFilePath();

		// 创建输出流对象
		ServletOutputStream outputStream = response.getOutputStream();

		// 以字节数组的形式读取文件
		byte[] bytes = FileUtil.readBytes(path);

		// 设置返回内容格式
		response.setContentType("application/octet-stream");

		// 把文件名按UTF-8取出并按ISO8859-1编码，保证弹出窗口中的文件名中文不乱码
		// 中文不要太多，最多支持17个中文，因为header有150个字节限制。
		// 这一步一定要在读取文件之后进行，否则文件名会乱码，找不到文件
		fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");

		// 设置下载弹窗的文件名和格式（文件名要包括名字和文件格式）
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

		// 返回数据到输出流对象中
		outputStream.write(bytes);

		// 关闭流对象
		IoUtil.close(outputStream);
	}

	// 查询所有
	@RequestMapping("/list")
	public LayuiPageInfo list(@RequestParam(value = "fileOriginName", required = false) String fileOriginName, @RequestParam(value = "fileSuffix", required = false) String fileSuffix, @RequestParam(value = "fileLocation", required = false) String fileLocation,
			@RequestParam(value = "page", defaultValue = "1") Integer current, @RequestParam(value = "limit", defaultValue = "20") Integer limit) {

		IPage<FileInfo> page = new Page<FileInfo>(current, limit);

		QueryWrapper<FileInfo> queryWrFileInfoer = new QueryWrapper<FileInfo>();

		if (!ObjectUtils.isEmpty(fileOriginName)) {
			queryWrFileInfoer.lambda().like(FileInfo::getFileOriginName, fileOriginName).or().like(FileInfo::getId, fileOriginName);
		}
		if (!ObjectUtils.isEmpty(fileSuffix)) {
			queryWrFileInfoer.lambda().like(FileInfo::getFileSuffix, fileSuffix);
		}
		if (!ObjectUtils.isEmpty(fileLocation)) {
			queryWrFileInfoer.lambda().like(FileInfo::getFileLocation, fileLocation);
		}

		queryWrFileInfoer.lambda().orderByDesc(FileInfo::getCreateTime);

		IPage<FileInfo> ipage = fileInfoService.page(page, queryWrFileInfoer);
		return LayuiPageInfo.ok(ipage.getTotal(), ipage.getRecords());
	}

	// 添加或者修改
	@RequestMapping("/saveOrUpdate")
	public LayuiPageInfo saveOrUpdate(@RequestBody @Valid FileInfo FileInfo) {

		fileInfoService.saveOrUpdate(FileInfo);
		return LayuiPageInfo.ok("数据保存成功 !");
	}

	// 查询详情
	@RequestMapping("/findById")
	public LayuiPageInfo findById(String id) {
		return LayuiPageInfo.ok(fileInfoService.getById(id));
	}

	// 查询所有（指定列）
	@RequestMapping("/listAll")
	public LayuiPageInfo listAll() {

		List<FileInfo> list = fileInfoService.listAll();
		return LayuiPageInfo.ok(list);
	}

	// 按照ID删除
	@RequestMapping("/delete")
	public LayuiPageInfo delete(String id) {

		fileInfoService.removeById(id);
		return LayuiPageInfo.ok("数据删除成功 !");
	}

	// 批量删除
	@RequestMapping("/batchDelete")
	public LayuiPageInfo batchDelete(@RequestBody String ids) {

		List<String> idList = Arrays.asList(ids.split(",")).stream().map(e -> {
			if (!ObjectUtils.isEmpty(e)) {
				return e;
			}
			return null;
		}).collect(Collectors.toList());

		fileInfoService.removeByIds(idList);
		return LayuiPageInfo.ok("成功删除了 [ " + idList.size() + " ] 条数据 ！");
	}

	// 删除所有
	@RequestMapping("/deleteAll")
	public LayuiPageInfo deleteAll() {

		fileInfoService.remove(new QueryWrapper<FileInfo>());
		return LayuiPageInfo.ok("成功删除表中所有数 !");
	}

}
